const mysql = require('mysql2');
const { write } = require('./config.cjs');

/** @type {mysql.Connection} */
let connection = null;

function connectMysql(evnet, option) {
    console.log("connectMysql", option);

    return new Promise((resolve, reject) => {
        connection = mysql.createConnection(option);
        connection.connect((error) => {
            if (error) return reject(error);

            write({ mysql: option });
            return resolve();
        });
    })
}

function isConnected(evnet) {
    return connection != null;
}

function getCurrentConnected(_) {
    console.log("connection", connection.authorized);

    if (!connection || !connection.authorized) return Promise.resolve(null);

    return new Promise((resolve, reject) => {
        connection.query("SELECT DATABASE();", (error, results, fields) => {
            if (error) return reject(error);

            console.log("DATABASE: ", results);

            return resolve(results);
        });
    })
}

function showDatabaseList(_, query) {
    return new Promise((resolve, reject) => {
        connection.query(`SHOW DATABASES ${ query && query.databaseName ? `LIKE %${ query.databaseName }%` : '' }`, (error, results, fields) => {
            if (error) return reject(error);

            return resolve(results);
        });
    })
}

function showTableList(_, query) {
    return new Promise((resolve, reject) => {
        connection.query(`
            SELECT *
            FROM information_schema.tables
            WHERE
            ${query && query.tableName ? `table_name like '%${query.tableName}%'` : ''}
            ${query && query.tableSchema ? `table_schema like '%${query.tableSchema}%'` : ''}
            ;
        `, (error, results, fields) => {
            if (error) return reject(error);

            return resolve(results);
        });
    })
}

function showTableDetail(_, { databaseName, tableName }) {
    if (!tableName) {
        return Promise.reject(new Error('table name is requisite'));
    }
    return new Promise((resolve, reject) => {
        connection.query(`DESCRIBE ${databaseName}.${tableName};`, (error, results, fields) => {
            if (error) return reject(error);

            return resolve(results);
        });
    })
}

function closeConnect() {
    if (!connection || !connection.authorized) return Promise.resolve();

    return new Promise((resolve, reject) => {
        connection.destroy();
        resolve();
    })
}

function query(_, {
    database,
    host,
    port,
    username,
    password,
    sql
}) {
    return new Promise((resolve, reject) => {
        const connection = mysql.createConnection({
            database,
            host,
            port,
            user: username,
            password
        });
        connection.query(sql, (error, results, fields) => {
            if (error) return reject(error);

            connection.destroy();
            console.log("query results: ", results);
            return resolve(results);
        });
    })
}

module.exports = {
    connectMysql,
    isConnected,
    getCurrentConnected,
    showDatabaseList,
    showTableList,
    showTableDetail,
    closeConnect,
    query
};